<template>
  <child-page>
    <div class="components-form-demo-advanced-search">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="标题" v-bind="formItemLayout">
          <a-input
            v-decorator="[
              'title',
              {
                initialValue: initInfo.title,
                rules: [
                  { required: true, message: '请输入标题！' },
                  {
                    validator: $validate.validateLength,
                    max: 50,
                    min: 1
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="分类" v-bind="formItemLayout">
          <a-select
            v-decorator="[
              'mid',
              {
                initialValue: initInfo.mid,
                rules: [{ required: true, message: '请选择分类！' }]
              }
            ]"
          >
            <a-select-option
              v-for="(item, key) in classify"
              :key="key"
              :value="item.id"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="描述" v-bind="formItemLayout">
          <a-input
            v-decorator="[
              'describe',
              {
                initialValue: initInfo.describe,
                rules: [
                  { required: true, message: '请输入描述内容！' },
                  {
                    validator: $validate.validateLength,
                    max: 100,
                    min: 1
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="关联项目" v-bind="formItemLayout">
          <a-select
            v-decorator="['project_id', { initialValue: initInfo.project_id }]"
          >
            <a-select-option
              v-for="(item, key) in relevance"
              :value="item.id"
              :key="key"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="封面图"
          v-bind="formItemLayout"
          help="建议图片宽高为：218px*216px"
        >
          <div class="clearfix">
            <a-upload
              v-decorator="[
                'upload',
                {
                  initialValue: initInfo.upload,
                  valuePropName: 'fileList',
                  getValueFromEvent: normFile,
                  rules: [{ required: true, message: '请上传封面图' }]
                }
              ]"
              accept="image/*"
              listType="picture-card"
              name="file"
              :multiple="false"
              :showUploadList="false"
              :action="$api.upload"
              :data="postData"
              :beforeUpload="beforeUpload"
            >
              <img
                v-if="imageUrl"
                :src="$api.picPre + imageUrl"
                alt="avatar"
                style="width: 120px"
              />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传封面图</div>
              </div>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item label="资讯详情" v-bind="formItemLayout" required>
          <div class="edit_container">
            <editor ref="content" :defaultValue="initInfo.info"></editor>
          </div>
        </a-form-item>
        <a-form-item label="状态" v-bind="formItemLayout">
          <a-select
            v-decorator="[
              'status',
              {
                initialValue: initInfo.status,
                rules: [{ required: true, message: '必选项' }]
              }
            ]"
          >
            <a-select-option value="1">
              启用
            </a-select-option>
            <a-select-option value="2">
              停用
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="推荐" v-bind="formItemLayout">
          <a-select
            v-decorator="[
              'is_recommend',
              {
                initialValue: initInfo.is_recommend,
                rules: [{ required: true, message: '必选项' }]
              }
            ]"
          >
            <a-select-option value="1">
              推荐
            </a-select-option>
            <a-select-option value="2">
              不推荐
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-row>
          <a-col :span="24" :style="{ textAlign: 'center' }">
            <a-button type="primary" html-type="submit">
              提交
            </a-button>
            <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
              重置
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </child-page>
</template>

<script>
import editor from "@/components/vueQuillEditor/index";
import childPage from "@/components/childPageContent/index";
import { getToken } from "@/tool/qiniu";
export default {
  name: "add",
  components: {
    editor,
    childPage
  },
  data() {
    return {
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      classify: [],
      relevance: [],
      content: "",
      str: "",
      stateValue: 1,
      recommendValue: 1,
      postData: {
        token: ""
      },
      initInfo: {
        upload: []
      },
      loading: false,
      imageUrl: ""
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          let content = this.$refs.content.getContent();
          if (!content) {
            this.$notification.warning({
              message: "请填写资讯详情！"
            });
          } else {
            let obj = JSON.parse(JSON.stringify(values));
            if (values.upload) {
              obj.pic = values.upload[0].response.key;
              delete obj.upload;
            }
            obj.info = content;
            let api = null;
            if (this.$route.name === "informationListEdit") {
              obj.type = 2;
              api = this.$api.editInfoList;
              obj.id = this.$route.params.id;
            } else {
              obj.type = 1;
              api = this.$api.addInfoList;
            }

            this.$ajax
              .post(api, obj)
              .then(() => {
                this.$notification.success({
                  message: "操作成功"
                });
                this.$router.push({ name: "informationList" });
              })
              .catch(err => {
                this.$notification.error({
                  message: err
                });
              });
          }
        }
      });
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "amusement/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 218;
        let height = 216;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为218px*216px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    normFile(e) {
      if (e.file.status === "uploading") {
        this.loading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageUrl = e.file.response.key;
        this.loading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    handleReset() {
      this.form.resetFields();
    },
    getClassInfo() {
      this.$ajax
        .get(this.$api.getInfoClassList, {
          page_size: 100,
          page: 1
        })
        .then(res => {
          this.classify = res.data;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    },
    getInfo() {
      this.$ajax
        .get(this.$api.detailInfoList, {
          id: this.$route.params.id
        })
        .then(res => {
          this.initInfo = res;
          this.initInfo.upload = [
            {
              uid: "1",
              status: "done",
              url: this.$api.picPre + res.pic,
              name: res.title,
              response: {
                key: res.pic
              }
            }
          ];
          this.imageUrl = res.pic;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    },
    getProjectInfo() {
      this.$ajax
        .get(this.$api.getProjectList, {
          page_size: 1000,
          page: 1
        })
        .then(res => {
          this.relevance = res.data;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    }
  },
  created() {
    this.getClassInfo();
    this.getProjectInfo();
    if (this.$route.name === "informationListEdit") {
      this.getInfo();
    }
  }
};
</script>

<style scoped></style>
